/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package oauth2

import (
	"github.com/google/go-querystring/query"
	"net/http"
	"encoding/json"
	"io/ioutil"
)

// 根据 code 获得 access token, code 在用户授权跳转后的 uri query 参数中获得, access token 包含了用户的 openid
func GetAuthAccessToken(appid, secret, code string) (token *AuthAccessToken, err error) {
	u, _ := query.Values(&accessConfig{
		AppID:     appid,
		Secret:    secret,
		Code:      code,
		GrantType: "authorization_code",
	})
	res, err := http.Get("https://api.weixin.qq.com/sns/oauth2/access_token?" + u.Encode())
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	token = &AuthAccessToken{}
	err = json.Unmarshal(data, token)
	if err != nil {
		return nil, err
	} else {
		return token, nil
	}
}

type accessConfig struct {
	AppID     string `url:"appid"`
	Secret    string `url:"secret"`
	Code      string `url:"code"`
	GrantType string `url:"grant_type"`
}

// auth access token 与 公众号 access token 是两个不同的东西, auth access token 包含了用户的 openid
// 或根据 AccessToken 近一步获取更多用户信息
type AuthAccessToken struct {
	AccessToken  string `json:"access_token"`
	ExpiresIn    int `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Openid       string `json:"openid"` // 一个公众号对应一个用户 openid, openid 是永久的
	Scope        string `json:"scope"`
}
